package com.awenhui.demo.core.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰转换帮助类
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/3/2 9:35
 */
public class HumpUtils {


    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String underLineToHump(String str) {
        if (str == null || str.trim().equals("")) return "";
        str = str.toLowerCase();
        Pattern pattern = Pattern.compile("[_]\\w");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            String w = matcher.group().trim();
            str = str.replace(w, w.toUpperCase().replace("_", ""));
        }

        return str;
    }

    /**
     * 驼峰转下划线
     *
     * @param str
     * @return
     */
    public static String humpToUnderLine(String str) {
        if (str == null || str.trim().equals("")) return "";
        //$0表示匹配到的字符串
        str= str.replaceAll("[A-Z]", "_$0").toLowerCase();
        //去掉第一个下划线
        if(str.startsWith("_"))str=str.substring(1);
        return str;
    }

    public static void main(String[] args) {
        String underlineStr1="user_id";
        String underlineStr2="dic_parent_name";
        String humpStr1="userName";
        String humpStr2="DicParentValue";

        String s = underLineToHump(underlineStr1);
        String s1 = underLineToHump(underlineStr2);
        String s2 = humpToUnderLine(humpStr1);
        String s3 = humpToUnderLine(humpStr2);
        System.out.println(s);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }


}